package com.hdcx.Minfresh.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.adapter.GoodListAdapter;
import com.hdcx.Minfresh.bean.GoodListWrapper;
import com.hdcx.Minfresh.bean.GsortWrapper;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.url.RequstCode;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.view.expandtabview.SearchTabLeft;
import com.hdcx.Minfresh.view.expandtabview.SearchTabMiddle;
import com.hdcx.Minfresh.view.expandtabview.SearchTabRight;
import com.hdcx.Minfresh.view.expandtabview.SearchTabView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Administrator on 2016/11/18.
 */

public class GoodListActivity extends BaseActivity {
    GoodListAdapter adapter;
    SearchTabView searchTabView;
    private SearchTabLeft viewLeft, viewLeft2;
    private SearchTabMiddle viewMiddle;
    private SearchTabRight viewRight;
    private ArrayList<View> mViewArray = new ArrayList<View>();
    String ClassId;
    private GsortWrapper gsortData;
    LRecyclerView recyclerView;
    LRecyclerViewAdapter mLRecyclerViewAdapter;
    Boolean isRefresh = false;
    int num = 1;
    int totleNum;
    GoodListWrapper data;
    private String px;
    public int ps;
    private String bt,kw;
    EditText ed_search;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodlist);
        initView();
        initData();
    }

    private void initView() {
        recyclerView = (LRecyclerView) findViewById(R.id.recycler_view);
        searchTabView = (SearchTabView) findViewById(R.id.expandtab_view);
        findViewById(R.id.bt_search).setOnClickListener(this);
        ed_search = (EditText) findViewById(R.id.ed_search);
        findViewById(R.id.tv_left).setOnClickListener(this);
        viewLeft = new SearchTabLeft(this);
        viewRight = new SearchTabRight(this);
        viewMiddle = new SearchTabMiddle(this);
        mViewArray.add(viewMiddle);
        mViewArray.add(viewLeft);
        mViewArray.add(viewRight);
    }

    private void initData() {
        ClassId = getIntent().getStringExtra("id");
        kw =getIntent().getStringExtra("kw");
        ArrayList<String> titles = new ArrayList<>();
        titles.add("全部分类");
        titles.add("价格");
        titles.add("筛选");
        searchTabView.setValue(titles, mViewArray);
        searchTabView.setTitle(titles.get(0), 0);
        searchTabView.setTitle(titles.get(1), 1);
        searchTabView.setTitle(titles.get(2), 2);
        adapter = new GoodListAdapter(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildPosition(view) % 3 != 0) {
                    outRect.right = 8;
                }
                outRect.top = 8;

            }
        });
        setRecycler();
        post_main();
        post_get_sort();
        initListener();
    }

    private void setRecycler() {
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                num = 1;
                isRefresh = true;
                post_main();
            }
        });
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (num * 20 < totleNum) {
                    // loading more
                    num = num + 1;
                    RecyclerViewStateUtils.setFooterViewState(GoodListActivity.this, recyclerView, 4, LoadingFooter.State.Loading, null);
                    post_main();
                } else {
                    RecyclerViewStateUtils.setFooterViewState(GoodListActivity.this, recyclerView, 4, LoadingFooter.State.TheEnd,null);

                }
            }
        });
    }

    private void post_get_sort() {
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("class", ClassId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.GSORT)
                .content(json.toString())
                .build()
                .execute(new Callback<GsortWrapper>() {
                    @Override
                    public GsortWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("GoodListActivity", "GoodListActivity--parseNetworkResponse--分类返回值"+json);
                        return new Gson().fromJson(json, GsortWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(GsortWrapper response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            gsortData = response;
                            viewMiddle.setData(response);
                            viewLeft.setData(response);
                        }
                    }
                });
    }

    /* 请求参数
     class	分类id
     page	页码
     size    每页数量  可选
     all=1   上级分类下的所有商品  可选  分类筛选*/
  /*  价格排序 可选
    px=1    低到高
            px=2	高到低

    筛选	可选
    ps=0  明日配送 默认
    ps=1	后天配送
            ps=2	大后天配送
            价格
    bt=0,4   0表示不限*/
    private void post_main() {
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("class", ClassId);
            json.put("page", num);
            json.put("size", "20");
            json.put("px", px==null?"0":px);
            json.put("ps", ps);
            json.put("bt", bt == null ? "" : bt);
            json.put("kw", kw == null ? "" : kw);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.GOODLIST)
                .content(json.toString())
                .build()
                .execute(new Callback<GoodListWrapper>() {
                    @Override
                    public GoodListWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("GoodListActivity", "GoodListActivity--parseNetworkResponse--搜索返回值"+json);
                        return new Gson().fromJson(json, GoodListWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(GoodListWrapper response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            totleNum = response.getCount();
                            if (num == 1) {
                                data = response;
                                adapter.setData(response);
                            } else {
                                data.getList().addAll(response.getList());
                                adapter.setData(data);
                            }
                        }
                        if (isRefresh) {
                            recyclerView.refreshComplete();
                        }
                    }
                });
    }

    private void initListener() {

        viewLeft.setOnSelectListener(new SearchTabLeft.OnSelectListener() {

            @Override
            public void getValue(String itemCode, String showText) {
                String districtcode = itemCode;
                // onRefresh(viewLeft, showText);
                px = itemCode;
                onRefresh(viewLeft, showText);
                num=1;
                post_main();
            }
        });

        viewMiddle.setOnSelectListener(new SearchTabMiddle.OnSelectListener() {

            @Override
            public void getValue(String itemLvTwocode, String showText) {

                String rank = itemLvTwocode;
                ClassId = rank;
                num=1;
                post_main();
                onRefresh(viewMiddle, showText);

            }
        });
        viewRight.setOKListen(new SearchTabRight.OnSelectRightListener() {


            @Override
            public void getValue(int ps, String showText) {
                searchTabView.onPressBack();
                GoodListActivity.this.ps = ps;
                num=1;
                bt = showText;
                post_main();
            }
        });
    }

    private void onRefresh(View view, String showText) {

        searchTabView.onPressBack();
        int position = getPositon(view);
        if (position >= 0 && !searchTabView.getTitle(position).equals(showText)) {
            searchTabView.setTitle(showText, position);
        }
        // Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();


    }

    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.bt_search:
               String search = ed_search.getText().toString().trim();
                if(search.equals("请输入关键字")){
                    Toast.makeText(this,"关键字不能为空！",Toast.LENGTH_SHORT).show();
                }else{
                    num =1;
                    kw = search;
                    post_main();
                }
        }
    }

    @Override
    public void onMyItemClick(Object data) {
        Intent intent = new Intent(this, DetailActivity.class);
        intent.putExtra("id", (String) data);
        startActivityForResult(intent, RequstCode.DETAIL);
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == RequstCode.DETAIL) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }
}
